﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Model;

namespace TaxiDispatchClient
{
    public partial class ComplaintForm : DevExpress.XtraEditors.XtraForm
    {
        public ComplaintForm()
        {
            InitializeComponent();                       
        }

    
        private string _title;
       
        private Thread _thread;

        private void ComplaintForm_Load(object sender, EventArgs e)
        {                      
           _thread = new Thread(BindGrid);
           _thread.Start();         
        }

        private void BindGrid()
        {
            try
            {                
                //string sql = "ComplaintsObject=0  ";                
                //if (buttonEdit_DriverPhone.Text !="")
                //{                
                //    sql += "and ComplaintBid like '%";
                //    sql += buttonEdit_DriverPhone.Text;
                //    sql += "%'";
                //}
                //sql += " order by t.id desc";
               
                // Aid 为乘客手机号  Bid为司机手机号  object 为0表示 乘客投诉司机 为1表示司机投诉乘客
                StringBuilder strWhere = new StringBuilder();
                strWhere.Append("ComplaintsObject=0 ");
                if (buttonEdit_DriverPhone.Text != "")
                {
                    strWhere.Append("and ComplaintBid like '%");
                    strWhere.Append(buttonEdit_DriverPhone.Text);
                    strWhere.Append("%' ");
                }
                if (MainForm.MyUserInfo.CompanyName!=Service.PowerConfig.MainCompanyName)
                {
                    strWhere.Append(" and CompanyName='");
                    strWhere.Append(MainForm.MyUserInfo.CompanyName);
                    strWhere.Append("'");
                }
                DataSet ds = MainForm.PositionService.ComplaintGetList(strWhere.ToString());
                BeginInvoke(new MethodInvoker(() =>
                {
                    gridControl1.DataSource = ds.Tables[0];                
                    if (buttonEdit_DriverPhone.Text== "")
                    {
                        gridView1.GroupPanelText = "投诉记录列表（被投诉对象：司机）";
                        _title = "投诉记录列表（被投诉对象：司机）";
                    }
                    DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);//
                    if (row != null)
                    {
                        textEdit_id.Text = row["id"].ToString();
                        textEdit_userPhone.Text = row["ComplaintAid"].ToString();
                        buttonEdit_DriverPho.Text = row["ComplaintBid"].ToString();
                        dateEdit_date.DateTime = DateTime.Parse(row["time"].ToString());
                        timeEdit_time.Time = DateTime.Parse(row["time"].ToString());
                        string strReason = row["Complaintreason"].ToString();
                        if (!comboBoxEdit_Reason.Properties.Items.Contains(strReason))
                            comboBoxEdit_Reason.Properties.Items.Add(strReason);
                        comboBoxEdit_Reason.Text = row["Complaintreason"].ToString();
                        btn_modify.Enabled = true;
                        btn_delete.Enabled = true;
                    }
                }));
              
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("正在中止线程"))
                {
                    Common.CommonRoutine.HandlingExceptions(ex);
                }
                else
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);                 
                    btn_select.Enabled = true;
                }               
            }
        
        }   

        private void simpleButton_add_Click(object sender, EventArgs e)
        {
            if (btn_add.Tag.ToString() == "新增")
            {
                gridControl1.Enabled = false;
                btn_add.Image = Properties.Resources.UserForm_btnsave001;
                btn_add.Tag = "保存";
                btn_cancel.Location = btn_modify.Location;
                btn_modify.Visible = false;
                btn_delete.Visible = false;
                btn_cancel.Visible = true;

                textEdit_id.Text = "";
                textEdit_userPhone.Text = "";                
                buttonEdit_DriverPho.Text = "";
                if (buttonEdit_DriverPhone.Text != "")
                {
                    buttonEdit_DriverPho.Text = buttonEdit_DriverPhone.Text;
                }
                memoEdit_reason.Text = "";
               
                dateEdit_date.DateTime  = DateTime.Now;
                timeEdit_time.Time = DateTime.Now;
                textEdit_userPhone.Enabled = true;
                buttonEdit_DriverPho.Enabled = true;
                timeEdit_time.Enabled = true;
                comboBoxEdit_Reason.Enabled = true;
              
                dateEdit_date.Enabled = true;
                timeEdit_time.Enabled = true;
            }
            else
            {
                if (!CheckInput()) return;
                string strComObj = "0";
                string strReason = comboBoxEdit_Reason.Properties.Items[comboBoxEdit_Reason.SelectedIndex].ToString();
                if (memoEdit_reason.Visible)
                    strReason = memoEdit_reason.Text;
                string strAid = textEdit_userPhone.Text;
                string strBid = buttonEdit_DriverPho.Text;          
                string strtime = dateEdit_date.Text +" "+ timeEdit_time.Text;

                try
                {
                   
                    ComplaintInfo  complaint = new ComplaintInfo 
                    {
                        Complaintsobject =int.Parse( strComObj ),
                        Complaintreason = strReason,
                        ComplaintAid = strAid,
                        ComplaintBid = strBid,
                        time = DateTime.Parse(strtime)
                    };
                    if (MainForm.PositionService.ComplaintAdd(complaint))
                    {
                        XtraMessageBox.Show("添加成功！");
                        btn_add.Tag = "新增";
                        btn_add.Image = Properties.Resources.UserForm_btnadd001;
                        gridControl1.Enabled = true;
                        btn_modify.Visible = true;
                        btn_delete.Visible = true;
                        btn_cancel.Visible = false;

                        textEdit_userPhone.Enabled = false;
                        buttonEdit_DriverPho.Enabled  = false;
                        comboBoxEdit_Reason.Enabled = false;
                        memoEdit_reason.Visible = false;
                        dateEdit_date.Enabled = false;
                        timeEdit_time.Enabled = false;

                        buttonEdit_DriverPhone.Text = "";                   
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("添加失败");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }
            
            }

        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
              DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);//
              if (row != null)
              {
                  textEdit_id.Text = row["id"].ToString();
                  textEdit_userPhone.Text = row["ComplaintAid"].ToString();
                  buttonEdit_DriverPho.Text = row["ComplaintBid"].ToString();
                  dateEdit_date.DateTime = DateTime.Parse(row["time"].ToString());
                  timeEdit_time.Time = DateTime.Parse(row["time"].ToString());
                  string strReason = row["Complaintreason"].ToString();
                  if (!comboBoxEdit_Reason.Properties.Items.Contains(strReason))
                      comboBoxEdit_Reason.Properties.Items.Add(strReason);
                  comboBoxEdit_Reason.Text   = row["Complaintreason"].ToString();
                  btn_modify.Enabled = true;
                  btn_delete.Enabled = true;
              }
        }

        private void simpleButton_delete_Click(object sender, EventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
            string id;
            if (row == null)
            {
                XtraMessageBox.Show("请选择要删除的投诉记录！");
                return;
            }
            id = row["id"].ToString();      
            if (XtraMessageBox.Show("确认删除流水号为【"+id+"】的记录？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    if (MainForm.PositionService.ComplaintDelete(int.Parse(id)))
                    {
                        XtraMessageBox.Show("删除成功！");
                        textEdit_userPhone.Text = "";
                        textEdit_id.Text = "";
                      //  comboBoxEdit_Reason.Text = "";                          
                        memoEdit_reason.Text = "";
                        buttonEdit_DriverPho.Text = "";
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("删除失败！");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }
            }
        }

        private void simpleButton_modify_Click(object sender, EventArgs e)
        {
            if (textEdit_id.Text == string.Empty)
            {
                XtraMessageBox.Show("请选择要修改的记录！");
                return;
            }
            if (btn_modify.Tag.ToString()== "修改")
            {

                gridControl1.Enabled = false;
                btn_modify.Tag = "保存";
                btn_modify.Image = Properties.Resources.UserForm_btnsave001;
                btn_cancel.Location = btn_modify.Location;
                btn_modify.Location = btn_add.Location;
                btn_cancel.Visible = true;
                btn_add.Visible = false;
                btn_delete.Visible = false;

                textEdit_userPhone.Enabled = true;
                buttonEdit_DriverPho.Enabled = true;
                timeEdit_time.Enabled = true; 
                comboBoxEdit_Reason.Enabled  = true;              
                dateEdit_date.Enabled = true;
                btn_select.Enabled = false;
                buttonEdit_DriverPhone.Enabled = false;
            }
            else
            {
                if (!CheckInput()) return;
                string strid = textEdit_id.Text;
                string strComObj = "0";
                string strReason = comboBoxEdit_Reason.Properties.Items[comboBoxEdit_Reason.SelectedIndex].ToString();
                if(memoEdit_reason.Visible)
                    strReason = memoEdit_reason.Text;
                string strAid = textEdit_userPhone.Text;
                string strBid = buttonEdit_DriverPho.Text;
                string strtime = dateEdit_date.Text + " " + timeEdit_time.Text;

                ComplaintInfo complaint = new ComplaintInfo
                {
                    id = int.Parse(strid),
                    Complaintsobject = int.Parse(strComObj),
                    Complaintreason = strReason,
                    ComplaintAid = strAid,
                    ComplaintBid = strBid,
                    time = DateTime.Parse(strtime) 

                }; 
                try
                {
                    if (MainForm.PositionService.ComplaintUpdate(complaint))
                    {
                        XtraMessageBox.Show("修改成功！");
                        gridControl1.Enabled = true;
                        btn_modify.Tag = "修改";
                        btn_modify.Location = btn_cancel.Location;
                        btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
                        btn_add.Visible = true;
                        btn_delete.Visible = true;
                        btn_cancel.Visible = false;

                        textEdit_userPhone.Enabled = false;
                        buttonEdit_DriverPho.Enabled = false;
                        timeEdit_time.Enabled = false; 
                        comboBoxEdit_Reason.Enabled = false;
                        memoEdit_reason.Visible = false;
                        dateEdit_date.Enabled = false;
                        _thread = new Thread(BindGrid);
                        _thread.Start();                 
                        btn_select.Enabled = true;
                        buttonEdit_DriverPhone.Enabled = true;
                    }
                    else
                    {
                        XtraMessageBox.Show("修改失败！");
                    }                    
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }
            }
        }

        private void simpleButton_cancel_Click(object sender, EventArgs e)
        {
            gridView1_RowClick(null,null);
            gridControl1.Enabled  = true;
            btn_add.Tag = "新增";
            btn_add.Image = Properties.Resources.UserForm_btnadd001;
            btn_add.Visible = true;
            btn_modify.Tag = "修改";
            btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
            btn_modify.Visible = true;
            btn_modify.Location = btn_cancel.Location;
            btn_cancel.Visible = false;
            btn_delete.Visible = true;

            textEdit_userPhone.Enabled = false;
            buttonEdit_DriverPho.Enabled  = false;
            timeEdit_time.Enabled = false;
            comboBoxEdit_Reason.Enabled = false;
            memoEdit_reason.Visible = false;
            dateEdit_date.Enabled = false;
            btn_select.Enabled = true;
            buttonEdit_DriverPhone.Enabled = true;

        }


        private void buttonEdit_DriverPhone_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DriverInfoForm driverInfoForm = new DriverInfoForm();
            driverInfoForm.ShowDialog();
            if (driverInfoForm.gridView1.FocusedRowHandle >= 0)
            {
                //btn_modify.Enabled = false;
                //btn_delete.Enabled = false;
                DataRow row = driverInfoForm.gridView1.GetDataRow(driverInfoForm.gridView1.FocusedRowHandle);
                buttonEdit_DriverPhone.Text = row["PhoneNumber"].ToString();
                string strName = row["Name"].ToString();
                string strWorkId = row["WorkId"].ToString();
                string strTaxiNo = row["taxino"].ToString();
                gridView1.GroupPanelText ="姓名： "+ strName +"       工号： "+strWorkId
                    + "         车牌号：" +strTaxiNo;
                string strPhone = buttonEdit_DriverPhone.Text;
                try
                {                  
                    _thread = new Thread(BindGrid);
                    _thread.Start();
                    _title = "手机号为" + strPhone + "的出租车被投诉记录清单";
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }
                
            } 
        }

        private bool CheckInput()
        {

            
            string strAid = textEdit_userPhone.Text.Trim();
            string strBid = buttonEdit_DriverPho.Text;
           
            if (strAid == string.Empty)
            {
                XtraMessageBox.Show("请输入投诉人(乘客)的电话！");
                textEdit_userPhone.Focus();
                return false; 
            }
            if (strBid == string.Empty)
            {
                XtraMessageBox.Show("请输入被投诉人(司机)的电话！");
                buttonEdit_DriverPho.Focus();
                return false; 
            }
            if (comboBoxEdit_Reason.SelectedIndex<0)
            {
                XtraMessageBox.Show("投诉理由不能为空！");
                comboBoxEdit_Reason.Focus();
                return false;

            }
            if (comboBoxEdit_Reason.Properties.Items[comboBoxEdit_Reason.SelectedIndex].ToString()=="其他原因")
            {
                if(memoEdit_reason.Text.Trim()=="")
                {
                    XtraMessageBox.Show("投诉理由不能为空！");
                    memoEdit_reason.Focus();
                    return false;
                }
               // if(memoEdit_reason.Text.Length>)
            }
            string strDate = dateEdit_date.DateTime.Date.ToShortDateString();
            string strTime = timeEdit_time.Time.ToShortTimeString();
            string strDatetime = strDate + " " + strTime;
            if(DateTime.Parse(strDatetime)>DateTime.Now)
            {
                XtraMessageBox.Show("投诉时间不能大于当前时间！");
                dateEdit_date.Focus();
                return false;
            }


            return true;
        }

        private void simpleButton_select_Click(object sender, EventArgs e)
        {
            buttonEdit_DriverPhone.Text = "";
            _thread = new Thread(BindGrid);
            _thread.Start();
        }

        private void buttonEdit_DriverPho_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DriverInfoForm driverInfoForm = new DriverInfoForm();
            driverInfoForm.ShowDialog();
            if (driverInfoForm.gridView1.FocusedRowHandle >= 0)
            {
                try
                {
                    DataRow row = driverInfoForm.gridView1.GetDataRow(driverInfoForm.gridView1.FocusedRowHandle);
                    string strPhone = row["PhoneNumber"].ToString();
                    buttonEdit_DriverPho.Text = strPhone;
                    
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }
            }
        }

        private void comboBoxEdit_Reason_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strReason = comboBoxEdit_Reason.Properties.Items[comboBoxEdit_Reason.SelectedIndex].ToString();
            memoEdit_reason.Visible = strReason == "其他原因";
        }

        #region  窗体控件效果
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;
            Cursor = Cursors.Arrow;
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
#endregion
       

        private void btn_exportToExcel_MouseClick(object sender, MouseEventArgs e)
        {
            saveFileDialog1.FileName = _title;
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView1.ExportToXls(saveFileDialog1.FileName);
            }
        }

        private void ComplaintForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null)
            {
                _thread.Abort();
            }
        }
                      
    } 
      

}